package com.gvfish.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.KeyFactory.Builder;
import com.gvfish.core.Page;
import com.gvfish.dao.ArticleDao;
import com.gvfish.dao.CategoryDao;
import com.gvfish.entity.Article;
import com.gvfish.entity.Category;

@Service
@Transactional
public class ArticleManager {
	private static final String SELECT_ART="select from com.gvfish.entity.Article ";
	
	@Autowired
	private ArticleDao articleDao;
	
	@Autowired
	private CategoryDao categoryDao;
	public void save(Article entity){
		articleDao.save(entity);
	}
	@Transactional
	public void save(Long categoryId,Article entity){
		articleDao.save(categoryId,entity);
	}
	
	@Transactional(readOnly=true)
	public List<Article> findAll(){
		return articleDao.findAll();
	}
	@Transactional(readOnly=true)
	public Article find(Long categoryId,Long id){
		Key key = getKey(categoryId, id);
		return articleDao.getById(key);
	}
	@Transactional
	public void del(Long categoryId,Long id){
		articleDao.del(getKey(categoryId, id));
	}
	public void del(Key key){
		articleDao.del(key);
	}
	public static Key getKey(Long categoryId,Long id){
		Builder builder = new KeyFactory.Builder(Category.class.getSimpleName(),
				categoryId);
		builder.addChild(Article.class.getSimpleName(), id);
		return builder.getKey();
	}
	public List<Article> findLastedArt(){
		String jdql = SELECT_ART+"order by editDate desc";
		return 	articleDao.getByJDQL(jdql,0,10);
	}
	public List<Article> findHotArt(){
		String jdql =SELECT_ART+ "order by view desc";
		return 	articleDao.getByJDQL(jdql,0,10);
	}
	public Page<Article> getByPage(Long categoryId,Page<Article> page){
		return articleDao.getTest(categoryId,page);
	}
	public List<Article> getByCategory(Long categoryId){
		return articleDao.getByCategory(categoryId);
	}
}
